﻿Public Class frm_venta
    Dim check As New Validar
    Dim accesoDatosProducto As New AccesoDatos("Producto")
    Dim accesoDatosVenta As New AccesoDatos("Venta")
    Dim accesoDatosDV As New AccesoDatos("DetalleVenta")
    Dim accesoDatosPagos As New AccesoDatos("Pagos")
    Dim accesoDatosEmpleado As New AccesoDatos("Empleado")


    Enum cerrar
        salir
        confirmar
    End Enum

    Dim accion As cerrar = cerrar.salir


    Public Sub confirmarVenta(ByVal grillaPagos As DataGridView)
        Dim venta As String
        Dim empleado As String = cmb_empleado.SelectedValue
        venta = "fecha = " & lbl_mostrarFecha.Text & ", montoTotal = " & lbl_mostrarMontoTotal.Text & ", esAnulada = 0, idEmpleado = " & empleado
        accesoDatosVenta.insertar(True, venta)
        Dim tipoPago As String
        Dim tarjeta As String
        Dim monto As String
        Dim idProductos As String
        Dim idVenta As String = txt_idVenta.Text
        Dim cant As String
        Dim talle As String
        Dim nroAuto As String


        For i As Integer = 0 To dgv_venta.RowCount - 1
            idProductos = CStr(dgv_venta.Item("Id".ToLower, i).Value)
            cant = CStr(dgv_venta.Item("Cantidad".ToLower, i).Value)
            talle = CStr(dgv_venta.Item("idTalle".ToLower, i).Value)
            accesoDatosDV.insertarDetalleVenta(txt_idVenta.Text, idProductos, talle, cant)
            accesoDatosDV.actualizarStockVenta(idProductos, talle, cant)
        Next

      
        For i As Integer = 0 To grillaPagos.RowCount - 1
            tipoPago = CStr(grillaPagos.Item("idTipo".ToLower, i).Value)
            tarjeta = CStr(grillaPagos.Item("idTarjeta".ToLower, i).Value)
            monto = CStr(grillaPagos.Item("Monto".ToLower, i).Value)
            nroAuto = CStr(grillaPagos.Item("nroAuto".ToLower, i).Value)
            accesoDatosPagos.insetarPagos(txt_idVenta.Text, tipoPago, tarjeta, nroAuto, monto)
        Next



        MessageBox.Show("Venta realizada con éxito", "Nueva Venta", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Me.Close()
        frm_menu.Show()

    End Sub


    Private Sub frm_venta_load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim consulta As String
        Dim tabla As New Data.DataTable

        txt_codigoProd.Focus()
        cmb_tallesDisponibles.SelectedIndex = -1

        consulta = "SELECT MAX(idVenta) + 1 AS 'idVenta' FROM Venta"
        lbl_mostrarFecha.Text = DateTime.Today
        txt_descuento.Enabled = False
        cmd_confirmarVenta.Enabled = False
        tabla = accesoDatosVenta.consulta(consulta)
        txt_idVenta.Text = tabla.Rows(0)("idVenta")
        txt_idVenta.Enabled = True


        cargarCombo(cmb_empleado, accesoDatosEmpleado.leerTabla("Empleado"), "idEmpleado", "nombre")
        cmb_empleado.SelectedIndex = -1

        cmd_buscar.Enabled = False
        cmd_agregarItem.Enabled = False
        cmd_quitarItem.Enabled = False
        txt_cantidadItems1.Enabled = False
        txt_codigoProd.Enabled = False
        cmb_tallesDisponibles.Enabled = False
        cmd_busquedaAvanzada.Enabled = False
    End Sub

    Private Sub cmd_salir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        frm_menu.Show()
        Me.Hide()
    End Sub

    Private Sub MenuPrincipalToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        frm_menu.Show()
        Me.Hide()
    End Sub

    Public Sub buscarPorId(ByVal id As String)
        dgv_producto.DataSource = accesoDatosProducto.consulta("select tp.nombre as 'Tipo Producto', tt.nombre as 'Tela', prod.descripcion as 'Descripcion', prod.precioVenta as 'Precio' from Producto prod INNER JOIN Proveedor prov on(prod.idProveedor=prov.idProveedor) INNER JOIN TipoTela tt on (tt.idTipoTela=prod.idTipoTela) INNER JOIN TipoProd tp on (tp.idTipoProd=prod.idTipoProd) where idProducto = " & id)
    End Sub

    Private Sub cmd_buscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_buscar.Click
        If IsNumeric(txt_codigoProd.Text) Then
            If accesoDatosProducto.validarExistencia("Producto", "idProducto", txt_codigoProd.Text) Then
                Dim consul As String
                dgv_producto.DataSource = Nothing
                txt_cantidadItems1.Text = ""
                lbl_mostrarCantidad.Text = ""

                buscarPorId(txt_codigoProd.Text)
                consul = "SELECT Talle.idTalle, Talle.nombre FROM Talle INNER JOIN Talle_Producto ON (Talle.idTalle = Talle_Producto.idTalle) WHERE Talle_Producto.cantidad > 0 and Talle_Producto.idProducto = " & txt_codigoProd.Text
                cargarCombo(cmb_tallesDisponibles, accesoDatosProducto.consulta(consul), "idTalle", "nombre")
                cmb_tallesDisponibles.Focus()
            Else
                MessageBox.Show("El codigo de producto ingresado no existe", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                txt_codigoProd.Text = ""
                txt_codigoProd.Focus()
            End If
        Else
            MessageBox.Show("Ingrese una clave numérica", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            txt_codigoProd.Text = ""
            txt_codigoProd.Focus()
        End If
    End Sub

    Private Sub cmb_tallesDisponibles_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmb_tallesDisponibles.SelectedIndexChanged
        If IsNumeric(cmb_tallesDisponibles.SelectedValue) Then
            Dim tabla As New Data.DataTable
            Dim consul As String
            consul = "select cantidad from Talle_Producto where idTalle = " & cmb_tallesDisponibles.SelectedValue & " and idProducto = " & txt_codigoProd.Text
            tabla = accesoDatosProducto.consulta(consul)
            lbl_mostrarCantidad.Text = tabla.Rows(0)("cantidad")
        Else
            lbl_mostrarCantidad.Text = ""
        End If
    End Sub

    Private Sub cargarCombo(ByRef combo As ComboBox, ByRef tablaACargar As Data.DataTable, ByVal indice As String, ByVal campo As String)
        combo.DataSource = Nothing
        combo.DataSource = tablaACargar
        combo.ValueMember = indice
        combo.DisplayMember = campo
    End Sub

    Private Sub frm_prod_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If accion = cerrar.salir Then
            If MessageBox.Show("¿Está seguro que desea salir?", "Confirmación", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                e.Cancel = False
                frm_menu.Show()
            Else
                e.Cancel = True
            End If
        End If
    End Sub

    Private Sub cmd_agregarItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_agregarItem.Click


        If validarBlancos() = True Then
            If validarExistenciaGrilla() Then
                MessageBox.Show("El producto que desea ingresar ya ha sido cargado", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
                dgv_producto.DataSource = Nothing
                txt_codigoProd.Text = ""
                txt_cantidadItems1.Text = ""
                lbl_mostrarCantidad.Text = ""
                cmb_tallesDisponibles.SelectedIndex = -1
                txt_codigoProd.Focus()
            Else
                Dim importe As Integer
                Dim id As String
                Dim descripcion As String
                Dim precioUni As Integer
                Dim cantidad As Integer
                Dim tabla As New Data.DataTable
                Dim consul As String
                Dim talle As String

                id = txt_codigoProd.Text
                consul = "select tp.nombre as 'Tipo Producto', tt.nombre as 'Tela', prod.descripcion as 'Descripcion', prod.precioVenta as 'Precio' from Producto prod INNER JOIN Proveedor prov on(prod.idProveedor=prov.idProveedor) INNER JOIN TipoTela tt on (tt.idTipoTela=prod.idTipoTela) INNER JOIN TipoProd tp on (tp.idTipoProd=prod.idTipoProd) where idProducto = " & id
                tabla = accesoDatosProducto.consulta(consul)
                precioUni = CInt(tabla.Rows(0)("Precio"))
                descripcion = tabla.Rows(0)("Tipo Producto") & " " & tabla.Rows(0)("Tela") & " " & tabla.Rows(0)("Descripcion") & " Talle " & cmb_tallesDisponibles.Text
                cantidad = txt_cantidadItems1.Text
                importe = cantidad * precioUni
                talle = cmb_tallesDisponibles.SelectedValue
                dgv_venta.Rows.Add(cantidad, id, descripcion, precioUni, importe, talle)

                dgv_producto.DataSource = Nothing
                txt_codigoProd.Text = ""
                lbl_mostrarCantidad.Text = ""
                txt_cantidadItems1.Text = ""
                cmb_tallesDisponibles.DataSource = Nothing
                txt_codigoProd.Focus()

                calcularSubtotal("Importe", dgv_venta)
                calcularTotal()
                cmd_confirmarVenta.Enabled = True
            End If
        End If

    End Sub

    Private Function validarBlancos() As Boolean
        Dim res As Boolean = True
        If check.validarBlanco(txt_codigoProd.Text) = True Then
            MessageBox.Show("Ingrese un producto.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            txt_codigoProd.Focus()
            res = False
        ElseIf check.validarBlanco(txt_cantidadItems1.Text) = True Then
            MessageBox.Show("Ingrese una cantidad.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            txt_cantidadItems1.Focus()
            res = False
        ElseIf check.validarComboBlanco(cmb_tallesDisponibles.SelectedIndex) = True Then
            MessageBox.Show("Ingrese un talle.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            cmb_tallesDisponibles.Focus()
            res = False
        End If
        Return res
    End Function

    Private Function validarExistenciaGrilla()
        Dim res As Boolean = False
        For i As Integer = 0 To dgv_venta.RowCount - 1
            If txt_codigoProd.Text = dgv_venta.Rows(i).Cells(1).Value And cmb_tallesDisponibles.SelectedValue = dgv_venta.Rows(i).Cells(5).Value Then
                res = True
            End If
        Next
        Return res
    End Function

    Private Sub calcularSubtotal(ByVal nombre_Columna As String, ByVal grilla As DataGridView)
        Dim total As Double = 0

        For i As Integer = 0 To grilla.RowCount - 1
            total = total + CDbl(grilla.Item(nombre_Columna.ToLower, i).Value)
        Next

        lbl_mostrarSubtotal.Text = total
    End Sub

    Private Sub calcularTotal()
        Dim total As Integer

        If chk_descuento.Checked = True Then
            total = CInt(lbl_mostrarSubtotal.Text) - CInt(txt_descuento.Text)
        Else
            total = lbl_mostrarSubtotal.Text
        End If
        lbl_mostrarMontoTotal.Text = total
    End Sub

    Private Sub cmd_quitarItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_quitarItem.Click
        If dgv_venta.Rows.Count = 0 Then

        Else
            dgv_venta.Rows.Remove(dgv_venta.CurrentRow)
            calcularSubtotal("Importe", dgv_venta)
            calcularTotal()
        End If

    End Sub

    Private Sub txt_descuento_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txt_descuento.Leave
        calcularTotal()
    End Sub

    Private Sub chk_descuento_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chk_descuento.CheckedChanged
        If chk_descuento.Checked = True Then
            txt_descuento.Enabled = True
        Else
            txt_descuento.Enabled = False
        End If
    End Sub

    Private Sub txt_cantidadItems_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If check.validarNumero(txt_cantidadItems1.Text) = False Then
            lbl_errorCantidad.Text = "*Ingrese Cantidad"
            txt_cantidadItems1.Focus()
        Else
            lbl_errorCantidad.Text = ""
            If txt_cantidadItems1.Text <> "" Then
                If CInt(txt_cantidadItems1.Text) > CInt(lbl_mostrarCantidad.Text) Then
                    MessageBox.Show("No hay suficiente stock, ingrese una cantidad menor.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    txt_cantidadItems1.Text = ""
                    txt_cantidadItems1.Focus()
                End If
            End If
        End If
    End Sub

    Private Sub cmd_confirmarVenta_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_confirmarVenta.Click
        If dgv_venta.Rows.Count = 0 Then
            MessageBox.Show("Agregue un item a la lista!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
        Else
            accion = cerrar.confirmar
            Me.Hide()
            frm_tipoPago.Show()
            frm_tipoPago.cargarMonto(lbl_mostrarMontoTotal.Text)
        End If

    End Sub

   

 Private Sub cmd_cancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_cancelar.Click
        lbl_mostrarMontoTotal.Text = ""
        lbl_mostrarSubtotal.Text = ""
        txt_descuento.Text = ""
        chk_descuento.Checked = False
        For i As Integer = 0 To dgv_venta.RowCount - 1
            dgv_venta.Rows.Remove(dgv_venta.Rows(0))
        Next
        cmd_confirmarVenta.Enabled = False
    End Sub


    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        lbl_mostrarHora.Text = Format(Now, "HH:mm:ss")
    End Sub


    Private Sub grb_producto_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles grb_producto.Enter

    End Sub

    Private Sub cmb_empleado_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmb_empleado.SelectedValueChanged
        If IsNumeric(cmb_empleado.SelectedValue) Then
            cmd_buscar.Enabled = True
            cmd_agregarItem.Enabled = True
            cmd_quitarItem.Enabled = True
            txt_cantidadItems1.Enabled = True
            txt_codigoProd.Enabled = True
            cmb_tallesDisponibles.Enabled = True
            cmd_busquedaAvanzada.Enabled = True

        End If
    End Sub

    Private Sub cmd_salir_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_salir.Click
        Me.Close()
    End Sub

    Private Sub cmd_busquedaAvanzada_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_busquedaAvanzada.Click
        frm_consultarProductos.ShowDialog()
    End Sub
End Class
